import React, { useEffect, useState, useRef } from 'react';
import { Message } from '../types';
import { Bot, AlertCircle, RotateCw, User, ExternalLink } from 'lucide-react';

interface ChatMessageProps {
  message: Message;
  onRetry?: (messageId: string) => void;
}

export function ChatMessage({ message, onRetry }: ChatMessageProps) {
  const isAI = message.sender === 'ai';
  const isFailed = message.status === 'failed';
  const isLoading = message.status === 'sending';
  const isEmpty = !message.content || message.content.trim() === '';
  
  // 添加的状态和引用
  const contentRef = useRef<HTMLDivElement>(null);
  const [showCursor, setShowCursor] = useState(isAI && isLoading && !isEmpty);
  
  // 对于AI发送中的消息添加闪烁光标效果
  useEffect(() => {
    if (isAI && isLoading && !isEmpty) {
      setShowCursor(true);
    } else if (isAI && !isLoading) {
      // 消息完成后，延迟一段时间再移除光标
      const timer = setTimeout(() => setShowCursor(false), 300);
      return () => clearTimeout(timer);
    }
  }, [isAI, isLoading, isEmpty, message.content]);
  
  // 如果是AI消息且内容为空且状态为发送中，则不显示此消息
  if (isAI && isEmpty && isLoading) {
    return null;
  }

  return (
    <div className={`flex gap-3 mb-6 ${isAI ? 'items-start' : 'items-start flex-row-reverse'}`}>
      {/* 用户/AI 头像 */}
      <div className={`flex-shrink-0 w-10 h-10 rounded-full flex items-center justify-center ${
        isAI ? 'bg-blue-100' : 'bg-gray-100'
      }`}>
        {isAI ? (
          <Bot className={`w-6 h-6 text-blue-600 ${isLoading ? 'animate-pulse' : ''}`} />
        ) : (
          <User className="w-6 h-6 text-gray-600" />
        )}
      </div>
      
      {/* 消息内容 */}
      <div className={`relative max-w-[80%] ${isAI ? 'pr-4' : 'pl-4'}`}>
        <div className={`p-4 rounded-lg ${
          isAI 
            ? 'bg-white border border-gray-200' 
            : 'bg-blue-600 text-white'
        }`}>
          {/* 消息内容 - 使用渐入动画 */}
          {message.content && (
            <div 
              ref={contentRef}
              className={`whitespace-pre-wrap ${isAI ? 'text-gray-800' : ''} ${
                isAI && isLoading ? 'animate-fade-in' : ''
              }`}
            >
              {message.content}
              {/* 显示光标 */}
              {showCursor && (
                <span className="inline-block w-2 h-4 ml-0.5 align-middle bg-blue-500 animate-blink"></span>
              )}
            </div>
          )}
          
          {/* 正在输入的提示 */}
          {isAI && isLoading && isEmpty && (
            <div className="flex items-center text-gray-500">
              <div className="flex space-x-1">
                <div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style={{ animationDelay: '0s' }}></div>
                <div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style={{ animationDelay: '0.2s' }}></div>
                <div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style={{ animationDelay: '0.4s' }}></div>
              </div>
            </div>
          )}
          
          {/* 错误消息 */}
          {isFailed && message.errorMessage && (
            <div className="mt-2 text-red-500 text-sm flex items-center">
              <AlertCircle className="w-4 h-4 mr-1" />
              <span>{message.errorMessage}</span>
            </div>
          )}
          
          {/* 知识库来源 */}
          {isAI && message.source && (
            <div className="mt-2 text-xs text-gray-500 flex items-center">
              <ExternalLink className="w-3 h-3 mr-1" />
              <span>来源: {message.source.fileName}</span>
            </div>
          )}
        </div>
        
        {/* 重试按钮 */}
        {isFailed && onRetry && (
          <button
            onClick={() => onRetry(message.id)}
            className="absolute top-0 right-0 bg-white p-1 rounded-full shadow border border-gray-200 hover:bg-gray-100"
            title="重试"
          >
            <RotateCw className="w-4 h-4 text-gray-600" />
          </button>
        )}
      </div>
    </div>
  );
}